<script setup lang="ts">
import type { MenuParams } from '@/apis/acl/menu/type'
import { ref } from 'vue'
import { addMenuService, updateMenuService } from '@/apis/acl/menu'

const dialogVisible = ref(false)

const menu = ref<MenuParams>({
  id: 0,
  pid: 0,
  name: '',
  code: '',
  level: 0
})

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入权限值', trigger: 'blur' }]
}
const open = (row: MenuParams) => {
  dialogVisible.value = true
  if (row.id) {
    Object.assign(menu.value, row)
  } else {
    Object.assign(menu.value, row)
    console.log(menu.value)
  }
}

// 确定
const formRef = ref()
const emits = defineEmits(['addEditMenu'])
const onConfirm = async () => {
  await formRef.value.validate()
  if (menu.value.id) {
    // 修改
    await updateMenuService(menu.value)
    emits('addEditMenu', 'update')
  } else {
    // 新增
    await addMenuService(menu.value)
    emits('addEditMenu', 'add')
  }

  dialogVisible.value = false
}

// 关闭dailog
const closeDialog = () => {
  formRef.value.resetFields()
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="menu.id ? '修改菜单' : '新增菜单'"
    @closed="closeDialog"
    style="width: 30%; height: 40%"
  >
    <template #default>
      <el-form
        label-width="100px"
        :model="menu"
        :rules="rules"
        style="margin: 40px 0"
        size="large"
        ref="formRef"
      >
        <el-form-item label="名称" prop="name">
          <el-input placeholder="请输入名称" v-model="menu.name"></el-input>
        </el-form-item>
        <el-form-item label="权限值" prop="code">
          <el-input placeholder="请输入权限值" v-model="menu.code"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>
